package 代码记录.指定公司代码练习记录.华为_2024.分值200;

import java.util.Scanner;

/**
 * @author zx
 * @create 2024-02-16 14:45
 * 自己能看懂的代码
 */
public class 计算三叉搜索树的高度_19 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] vals = new int[n];
        for (int i = 0; i < n; i++) {
            vals[i] = sc.nextInt();
        }
        Node root = new Node(vals[0]);
        for (int i = 1; i < n; i++) {
            dfs(root, vals[i]);//以vals的第一个元素为根节点建立三叉搜索树
        }
        int res = maxHeight(root);
        System.out.println(res);
    }

    //根据传入的root,建立三叉搜索树
    static void dfs(Node curNode, int val) {
        if (curNode.val - val < -500) {
            if (curNode.left == null) {
                curNode.left = new Node(val);
                return;
            }
            dfs(curNode.left, val);
        } else if (curNode.val - val > 500) {
            if (curNode.right == null) {
                curNode.right = new Node(val);
                return;
            }
            dfs(curNode.right, val);
        } else {
            if (curNode.mid == null) {
                curNode.mid = new Node(val);
                return;
            }
            dfs(curNode.mid, val);
        }
    }

    static int maxHeight(Node node) {
        if (node == null) {
            return 0;
        }
        int left = maxHeight(node.left) + 1;
        int mid = maxHeight(node.mid) + 1;
        int right = maxHeight(node.right) + 1;
        return Math.max(left,Math.max(mid,right));
    }

    static class Node {
        int val;
        Node left, mid, right;

        Node(int val) {
            this.val = val;
        }
    }
}
